import React, { useRef, useState } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { PlusOutlined, ExportOutlined, ImportOutlined } from '@ant-design/icons';
import { Button, Card, message, Modal, Space, Tag, Form, DatePicker, Input, Select } from 'antd';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { useRequest } from '@umijs/max';
import moment from 'moment';

import { addBorrowRecord, deleteBorrowRecord, getBorrowRecordPage, returnBorrowRecord, updateBorrowRecord } from '@/services/borrowApi';
import BorrowForm from './components/BorrowForm';

const { RangePicker } = DatePicker;
const { Option } = Select;

/**
 * 物资外借登记页面
 */
const MaterialBorrowPage: React.FC = () => {
  // 表格引用
  const actionRef = useRef<ActionType>();
  
  // 状态管理
  const [formVisible, setFormVisible] = useState<boolean>(false);
  const [currentRecord, setCurrentRecord] = useState<MATERIAL_BORROW.BorrowRecord | undefined>(undefined);
  const [returnModalVisible, setReturnModalVisible] = useState<boolean>(false);
  const [returnForm] = Form.useForm();
  
  // 表格列定义
  const columns: ProColumns<MATERIAL_BORROW.BorrowRecord>[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 48,
    },
    {
      title: '物资名称',
      dataIndex: 'materialName',
      ellipsis: true,
    },
    {
      title: '借用人',
      dataIndex: 'borrowerName',
      ellipsis: true,
    },
    {
      title: '联系电话',
      dataIndex: 'borrowerPhone',
      ellipsis: true,
    },
    {
      title: '班级',
      dataIndex: 'borrowerClass',
      ellipsis: true,
    },
    {
      title: '用途',
      dataIndex: 'purpose',
      ellipsis: true,
    },
    {
      title: '借用数量',
      dataIndex: 'borrowQuantity',
      width: 80,
    },
    {
      title: '借用时间',
      dataIndex: 'borrowTime',
      valueType: 'dateTime',
      ellipsis: true,
    },
    {
      title: '归还时间',
      dataIndex: 'returnTime',
      valueType: 'dateTime',
      ellipsis: true,
      render: (_, record) => {
        return record.returnTime ? moment(record.returnTime).format('YYYY-MM-DD HH:mm:ss') : '-';
      },
    },
    {
      title: '状态',
      dataIndex: 'isReturned',
      width: 80,
      render: (_, record) => {
        return record.isReturned ? (
          <Tag color="green">已归还</Tag>
        ) : (
          <Tag color="orange">借用中</Tag>
        );
      },
    },
    {
      title: '归还状态',
      dataIndex: 'isIntact',
      width: 80,
      render: (_, record) => {
        if (!record.isReturned) return '-';
        return record.isIntact ? (
          <Tag color="green">完好</Tag>
        ) : (
          <Tag color="red">损坏</Tag>
        );
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 180,
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            setCurrentRecord(record);
            setFormVisible(true);
          }}
        >
          编辑
        </a>,
        !record.isReturned && (
          <a
            key="return"
            onClick={() => {
              setCurrentRecord(record);
              setReturnModalVisible(true);
            }}
          >
            归还
          </a>
        ),
        <a
          key="delete"
          onClick={() => {
            Modal.confirm({
              title: '确认删除',
              content: `确定要删除 ${record.materialName} 的借用记录吗？`,
              onOk: async () => {
                try {
                  if (record.id) {
                    const response = await deleteBorrowRecord(record.id);
                    if (response.code === 200) {
                      message.success('删除成功');
                      actionRef.current?.reload();
                    } else {
                      message.error(response.message || '删除失败');
                    }
                  }
                } catch (error) {
                  message.error('删除失败');
                  console.error('删除物资外借记录失败:', error);
                }
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  // 处理归还物资
  const handleReturn = async () => {
    try {
      const values = await returnForm.validateFields();
      if (currentRecord?.id) {
        const response = await returnBorrowRecord(
          currentRecord.id,
          values.isIntact,
          values.remark,
        );
        if (response.code === 200) {
          message.success('归还成功');
          setReturnModalVisible(false);
          returnForm.resetFields();
          actionRef.current?.reload();
        } else {
          message.error(response.message || '归还失败');
        }
      }
    } catch (error) {
      console.error('归还物资失败:', error);
    }
  };

  // 处理表单提交
  const handleFormSubmit = async (values: MATERIAL_BORROW.BorrowRecord) => {
    try {
      let response;
      if (currentRecord?.id) {
        // 更新
        response = await updateBorrowRecord({
          ...values,
          id: currentRecord.id,
        });
      } else {
        // 新增
        response = await addBorrowRecord(values);
      }

      if (response.code === 200) {
        message.success(currentRecord?.id ? '更新成功' : '添加成功');
        setFormVisible(false);
        setCurrentRecord(undefined);
        actionRef.current?.reload();
      } else {
        message.error(response.message || (currentRecord?.id ? '更新失败' : '添加失败'));
      }
    } catch (error) {
      message.error(currentRecord?.id ? '更新失败' : '添加失败');
      console.error('提交物资外借记录失败:', error);
    }
  };

  return (
    <PageContainer
      header={{
        title: '物资外借登记',
      }}
    >
      <Card>
        <ProTable<MATERIAL_BORROW.BorrowRecord>
          headerTitle="物资外借记录"
          actionRef={actionRef}
          rowKey="id"
          search={{
            labelWidth: 120,
          }}
          toolBarRender={() => [
            <Button
              key="add"
              type="primary"
              onClick={() => {
                setCurrentRecord(undefined);
                setFormVisible(true);
              }}
              icon={<PlusOutlined />}
            >
              新增借用
            </Button>,
          ]}
          request={async (params) => {
            // 转换查询参数
            const queryParams: MATERIAL_BORROW.BorrowQueryParams = {
              current: params.current,
              pageSize: params.pageSize,
              materialName: params.materialName,
              borrowerName: params.borrowerName,
              borrowerPhone: params.borrowerPhone,
              borrowerClass: params.borrowerClass,
              isReturned: params.isReturned,
            };

            // 处理时间范围
            if (params.borrowTime && params.borrowTime.length === 2) {
              queryParams.borrowStartTime = params.borrowTime[0];
              queryParams.borrowEndTime = params.borrowTime[1];
            }

            try {
              const response = await getBorrowRecordPage(queryParams);
              return {
                data: response.data.records,
                success: response.code === 200,
                total: response.data.total,
              };
            } catch (error) {
              console.error('获取物资外借记录失败:', error);
              return {
                data: [],
                success: false,
                total: 0,
              };
            }
          }}
          columns={columns}
          form={{
            // 由于后端接口使用 POST 方法，这里配置为 false
            syncToUrl: false,
          }}
        />
      </Card>

      {/* 物资外借表单 */}
      <BorrowForm
        visible={formVisible}
        record={currentRecord}
        onCancel={() => {
          setFormVisible(false);
          setCurrentRecord(undefined);
        }}
        onSubmit={handleFormSubmit}
      />

      {/* 归还物资弹窗 */}
      <Modal
        title="归还物资"
        open={returnModalVisible}
        onOk={handleReturn}
        onCancel={() => {
          setReturnModalVisible(false);
          returnForm.resetFields();
        }}
      >
        <Form form={returnForm} layout="vertical">
          <Form.Item
            name="isIntact"
            label="归还状态"
            rules={[{ required: true, message: '请选择归还状态' }]}
          >
            <Select placeholder="请选择归还状态">
              <Option value={true}>完好</Option>
              <Option value={false}>损坏</Option>
            </Select>
          </Form.Item>
          <Form.Item name="remark" label="备注">
            <Input.TextArea rows={4} placeholder="请输入备注信息" />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default MaterialBorrowPage;